package com.kelvem.saas.workbanch.fsm;

import com.kelvem.saas.workbanch.core.experiment.SpringStartupTimeline;
import com.kelvem.saas.workbanch.fsm.anno.Fsm;
import com.kelvem.saas.workbanch.fsm.dao.BaseDao;
import com.kelvem.saas.workbanch.fsm.resolver.FsmResolver;
import com.kelvem.saas.workbanch.fsm.resolver.MapperResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @description: bean创建之后的操作, 会调用postProcessAfterInitialization
 *
 * @author kelvem
 **/
@Slf4j
@Component
public class FsmBeanCreateProcessor implements BeanPostProcessor {
    
//    /**
//     * bean初始化之前的操作
//     */
//    @Override
//    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//        log.debug("[bean] " + beanName + " before");
//
//
//        return bean;
//    }
    
    /**
     * bean创建之后的操作
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        SpringStartupTimeline.setPostProcessAfterInitializationStart();
        log.debug("[bean] " + beanName + " after");

        if (bean instanceof BaseDao) {
            SpringStartupTimeline.setMapperStart();
            MapperResolver.resolve(bean, beanName);
            SpringStartupTimeline.setMapperStart();
        } else if (isCglibProxyClass(bean.getClass())) {
            // Get the superclass which is the original class
            Class<?> originalClass = bean.getClass().getSuperclass();
            if (originalClass.getAnnotation(Fsm.class) != null) {
                SpringStartupTimeline.setFsmStart();
                FsmResolver.resolve(bean, beanName);
                SpringStartupTimeline.setFsmEnd();
            }

        } else if (bean.getClass().getAnnotation(Fsm.class) != null) {
            SpringStartupTimeline.setFsmStart();
            FsmResolver.resolve(bean, beanName);
            SpringStartupTimeline.setFsmEnd();
        } else {
//            System.err.println(bean.getClass());
        }

        SpringStartupTimeline.setPostProcessAfterInitializationEnd();
        return bean;
    }

    private boolean isCglibProxyClass(Class<?> clazz) {
        return clazz.getName().contains("$$EnhancerBySpringCGLIB$$");
    }
}